package com.ruoyi.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.mapper.HotelMapper;
import com.ruoyi.mapper.HouseMapper;
import com.ruoyi.mapper.OrderMapper;
import com.ruoyi.mapper.RPMapper;
import com.ruoyi.service.GroundService;
import com.ruoyi.service.HotelService;
import com.ruoyi.service.LogService;
import com.ruoyi.service.RPService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

@Service
public class RPServiceImpl implements RPService {

    private static Logger hotelSuccess = LoggerFactory.getLogger("hotel_success");

    @Value("${eLong.misSupplierId}")
    private String misSupplierId;

    @Autowired
    HouseMapper houseMapper;

    @Autowired
    RPMapper rpMapper;

    @Autowired
    GroundService groundService;

    @Autowired
    HotelService hotelService;

    @Autowired
    HotelMapper hotelMapper;

    @Autowired
    LogService logService;

    @Autowired
    OrderMapper orderMapper;

    @Override
    @Transactional
    public int postPriceEnter(Map map) {
        JSONArray jsonArray = JSONArray.parseArray(map.get("dataStr").toString());
        // 酒店ID
        String hotelId = map.get("hotelId").toString();
        // 所属该酒店的周末星期
        List<Integer> hotelWeekEnd = hotelMapper.getHotelWeekEndByHotelId(hotelId);
        Long userId = SecurityUtils.getUserId();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String startTime = jsonObject.getJSONArray("RQRange").getString(0);
            String endTime = jsonObject.getJSONArray("RQRange").getString(1);
            String rpId = jsonObject.getString("rpId");
            String houseId = jsonObject.getString("houseId");
            String rpPrice = jsonObject.getString("rpPrice");
            String rpPriceWeekend = "";
            // 判断是否填写周末价格
            boolean isWeekendPrice = false;
            if (jsonObject.get("rpPriceWeekend") != null && !"".equals(jsonObject.getString("rpPriceWeekend")) && jsonObject.getInteger("rpPriceWeekend") != 0) {
                isWeekendPrice = true;
            }
            if (isWeekendPrice) {
                rpPriceWeekend = jsonObject.getString("rpPriceWeekend");
                // 如果填写了
                logService.insertHouseRpPriceLog(hotelId, houseId, rpId, userId, "修改采购价,将" + startTime + "至" + endTime + "的采购价修改为【" + rpPrice + "】,周末价为【" + rpPriceWeekend + "】");
            } else {
                // 如果没填写
                logService.insertHouseRpPriceLog(hotelId, houseId, rpId, userId, "修改采购价,将" + startTime + "至" + endTime + "的采购价修改为【" + rpPrice + "】");
            }

            // 直接查有没有,有就update,没有就insert
            List<String> datesInRange = DateUtils.getDatesInRange(startTime, endTime);
            for (String day : datesInRange) {
                String price;
                if (isWeekendPrice) {
                    // 如果填写了周末价,判断当日是否的周末
                    boolean dateInWeekdays = DateUtils.isDateInWeekdays(day, hotelWeekEnd);
                    if (dateInWeekdays) {
                        // 属于周末就周末价格
                        price = rpPriceWeekend;
                    } else {
                        // 不属于周末就平时价格
                        price = rpPrice;
                    }
                } else {
                    // 没有填写则是平时价格
                    price = rpPrice;
                }

                Map map1 = new HashMap();
                map1.put("houseId", houseId);
                map1.put("startTime", day);
                map1.put("endTime", day);
                List<Map> houseDayList = houseMapper.getHouseDayList(map1);
                // 如果房型没有该日期,就insert一条
                if (houseDayList.size() == 0) {
                    Map map2 = new HashMap();
                    map2.put("houseDay", day);
                    map2.put("houseId", houseId);
                    map2.put("houseStatus", 0);
                    houseMapper.insertHouseDay(map2);
                    houseDayList = houseMapper.getHouseDayList(map1);
                }
                // 这里只能insert或update rp数据,如果删除就会把艺龙卖价,房态一起删了,可以用houseDayId和rpId判断
                Map map3 = houseDayList.get(0);
                Map map2 = new HashMap();
                map2.put("rpId", rpId);
                map2.put("houseDayId", map3.get("houseDayId").toString());
                List<Map> rpDataList = rpMapper.getRPDataList(map2);
                if (rpDataList.size() == 0) {
                    // insert
                    map2.put("rpStatus", 0);
                    map2.put("rpPrice", price);
                    rpMapper.insertRpData(map2);
                } else {
                    // update
                    map2.put("rpPrice", price);
                    rpMapper.updateRpData(map2);
                }
            }
        }
        return 1;
    }

    @Override
    public AjaxResult postUpdateRpDimension(JSONObject jsonObject) {
        JSONArray rqRange = jsonObject.getJSONArray("rqRange");
        String startTime = rqRange.getString(0);
        String endTime = rqRange.getString(1);
        String ePrice = jsonObject.getString("ePrice");
        String ePriceWeekend = jsonObject.getString("ePriceWeekend");
        String rpId = jsonObject.getString("rpId");
        String houseId = jsonObject.getString("houseId");
        String hotelId = jsonObject.getString("hotelId");
        Long userId = SecurityUtils.getUserId();
        boolean isWeekendPrice;
        if (ePriceWeekend == null || "".equals(ePriceWeekend)) {
            // 没填写
            isWeekendPrice = false;
            ePriceWeekend = ePrice;
        } else {
            // 填写了
            isWeekendPrice = true;
        }

        List<Integer> hotelWeekEnd = hotelMapper.getHotelWeekEndByHotelId(hotelId);
        List<String> datesInRange = DateUtils.getDatesInRange(startTime, endTime);
        List<Map<String, Object>> priceIntervals = new ArrayList<>();

        // 初始化第一个区间
        int weekType = DateUtils.isDateInWeekdays(datesInRange.get(0), hotelWeekEnd) ? 1 : 0;
        List<String> currentDays = new ArrayList<>();
        currentDays.add(datesInRange.get(0));
        for (int i = 1; i < datesInRange.size(); i++) {
            String day = datesInRange.get(i);
            boolean isWeekend = DateUtils.isDateInWeekdays(day, hotelWeekEnd);

            // 如果当前日的类型与之前不同，则打包之前的区间并开始新的区间
            if ((isWeekend ? 1 : 0) != weekType) {
                addPriceInterval(priceIntervals, new ArrayList<>(currentDays), weekType == 1 ? ePriceWeekend : ePrice);
                currentDays.clear();
                weekType = isWeekend ? 1 : 0;
            }
            currentDays.add(day);
        }
        addPriceInterval(priceIntervals, new ArrayList<>(currentDays), weekType == 1 ? ePriceWeekend : ePrice);

        // 在这里增加校验逻辑
        for (Map<String, Object> priceInterval : priceIntervals) {
            List<String> days = (List) priceInterval.get("days");
            BigDecimal price = new BigDecimal(priceInterval.get("ePrice").toString());
            for (String day : days) {
                // 获取这一日的产品价格
                List<Map> rpPriceByRpIdAndTime = rpMapper.getRpPriceByRpIdAndTime(rpId, day, DateUtils.getNextDay(day));
                if (rpPriceByRpIdAndTime.size() > 0) {
                    BigDecimal rpPrice = new BigDecimal(rpPriceByRpIdAndTime.get(0).get("rpPrice").toString());
                    // 使用销售价和采购价对比
                    int comparisonResult = price.compareTo(rpPrice);
                    if (comparisonResult == -1 || comparisonResult == 0) {
                        return AjaxResult.error("销售价必须高于采购价");
                    }
                } else {
                    return AjaxResult.error("未获取" + day + "日采购价");
                }
            }
        }

        JSONObject jsonObject1 = groundService.updatePriceInfoOpen(hotelId, 0, "RMB", "NET_PRICE", rpId, houseId, priceIntervals);
        if (jsonObject1.getInteger("retcode") == 0) {
            for (Map map : priceIntervals) {
                List<String> days = (List) map.get("days");
                if (days.size() > 0) {
                    String price = map.get("ePrice").toString();
                    String startTime1 = days.get(0);
                    String endTime1 = days.get(days.size() - 1);
                    Map map1 = new HashMap();
                    map1.put("houseId", houseId);
                    map1.put("startTime", startTime1);
                    map1.put("endTime", endTime1);
                    List<Map> houseDayList = houseMapper.getHouseDayList(map1);
                    for (Map map2 : houseDayList) {
                        String houseDayId = map2.get("houseDayId").toString();
                        Map map3 = new HashMap();
                        map3.put("ePrice", price);
                        map3.put("rpId", rpId);
                        map3.put("houseDayId", houseDayId);
                        map3.put("rpStatus", 1);
                        rpMapper.updateRpData(map3);
                    }
                }
            }
            if(isWeekendPrice){
                logService.insertHouseRpPriceLog(hotelId, houseId, rpId, userId, "修改出售价,将" + startTime + "至" + endTime + "的出售价修改为【" + ePrice + "】,周末价为【"+ ePriceWeekend + "】");
            } else {
                logService.insertHouseRpPriceLog(hotelId, houseId, rpId, userId, "修改出售价,将" + startTime + "至" + endTime + "的出售价修改为【" + ePrice + "】");
            }
        }
        return AjaxResult.success();
    }

    // 辅助方法：创建一个新的价格区间并添加到列表中
    private static void addPriceInterval(List<Map<String, Object>> intervals, List<String> days, String price) {
        if (!days.isEmpty()) {
            Map<String, Object> interval = new HashMap<>();
            interval.put("days", days);
            interval.put("ePrice", price);
            intervals.add(interval);
        }
    }

    @Override
    public List<Map> getRpList(Map map) {
        String hotelId = map.get("hotelId").toString();
        List<Map> rpList = rpMapper.getRpList(hotelId);
        return rpList;
    }

    @Override
    @Transactional
    public AjaxResult goOnline(JSONObject jsonObject) {
        try {
            String hotelId = jsonObject.getString("hotelId");
            String houseId = jsonObject.getString("houseId");
            String rpId = jsonObject.getString("rpId");

            String supplierHotelId = hotelId;
            String supplierHotelName = jsonObject.getString("hotelName");
            String supplierRoomTypeId = houseId;
            String supplierRoomTypeName = jsonObject.getString("houseName");
            String supplierRatePlanId = rpId;
            String supplierRatePlanName = jsonObject.getString("rpName");
            String mHotelId = jsonObject.getString("eHotelId");
            String mHotelName = jsonObject.getString("eHotelName");
            String mRoomId = jsonObject.getString("eHouseId");
            String mRoomName = jsonObject.getString("eHouseName");
            JSONObject resJonObj = groundService.pushAutoMapping(supplierHotelId, supplierHotelName, supplierRoomTypeId, supplierRoomTypeName, supplierRatePlanId, supplierRatePlanName, mHotelId, mHotelName, mRoomId, mRoomName, misSupplierId);
            // 先验证上线接口是否成功
            if (resJonObj.getInteger("retcode") == 0) {
                Map map1 = new HashMap();
                map1.put("rpId", supplierRatePlanId);
                map1.put("houseId", houseId);
                map1.put("isOnline", 1);
                houseMapper.updateHouseByMap(map1);
                rpMapper.updateRpByMap(map1);
                logService.insertHouseRpPriceLog(hotelId, houseId, null, SecurityUtils.getUserId(), "上线成功");

                    /*
                    // 拿到酒店信息
                    JSONObject jsonObject2 = jsonObject1.getJSONArray("mappingList").getJSONObject(0);
                    String elongHotelID = jsonObject2.getString("elongHotelID");
                    String elongHotelName = jsonObject2.getString("elongHotelName");
                    Map map2 = new HashMap();
                    map2.put("hotelId", supplierHotelId);
                    map2.put("sonElongHotelID", elongHotelID);
                    map2.put("elongHotelName", elongHotelName);
                    hotelMapper.updateHotelByMap(map2);
                    // 拿到这个酒店的房型信息
                    JSONArray jsonArray = jsonObject2.getJSONArray("roomTypeMappingList");
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject jsonObject3 = jsonArray.getJSONObject(i);
                        String elongRoomTypeID = jsonObject3.getString("elongRoomTypeID");
                        String elongRoomTypeName = jsonObject3.getString("elongRoomTypeName");
                        String supplierRoomTypeID = jsonObject3.getString("supplierRoomTypeID");
                        Map map = new HashMap();
                        map.put("elongRoomTypeID", elongRoomTypeID);
                        map.put("elongRoomTypeName", elongRoomTypeName);
                        map.put("houseId", supplierRoomTypeID);
                        houseMapper.updateHouseByMap(map);

                        // 拿到这个房型的产品
                        JSONArray jsonArray1 = jsonObject3.getJSONArray("ratePlanMappingList");
                        for (int j = 0; j < jsonArray1.size(); j++) {
                            JSONObject jsonObject4 = jsonArray1.getJSONObject(j);
                            String elongRatePlanID = jsonObject4.getString("elongRatePlanID");
                            String elongRatePlanName = jsonObject4.getString("elongRatePlanName");
                            String supplierRatePlanID = jsonObject4.getString("supplierRatePlanID");
                            Map map1 = new HashMap();
                            map1.put("elongRatePlanID", elongRatePlanID);
                            map1.put("elongRatePlanName", elongRatePlanName);
                            map1.put("rpId", supplierRatePlanID);
                            map1.put("isOnline", 1);
                            rpMapper.updateRpByMap(map1);
                        }
                    }
                     */
                return AjaxResult.success();
            }
            return AjaxResult.error("上线失败");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.error("上线失败");
    }

    @Override
    @Transactional
    public AjaxResult postShelvesRp(JSONObject jsonObject) {
        // step1:找到这个产品的房型ID以及酒店ID
        String rpId = jsonObject.getString("rpId");
        Map rpObj = rpMapper.getRpObjByRpId(rpId);
        String houseId = rpObj.get("houseId").toString();
        String hotelId = rpObj.get("hotelId").toString();

        // step2:找到该产品价格的最小时间及最大时间,调用接口设置成价格无效
        List<String> rpHouseDayList = rpMapper.getRpHouseDayListByRpId(rpId);
        if (rpHouseDayList.size() > 0) {
            String minDate = rpHouseDayList.get(0);
            String maxDate = rpHouseDayList.get(rpHouseDayList.size() - 1);
            JSONObject res = groundService.updatePriceInfoClose(hotelId, minDate, maxDate, rpId, houseId);
            // step3:设置价格无效后删除该产品的时间维度数据
            if (res.getInteger("retcode") == 0) {
                rpMapper.deleteRpDataByRpId(rpId);
            }
        }
        // step4:艺龙下线
        JSONObject res1 = groundService.offlineMapping("RatePlan", hotelId, houseId, rpId);
        int i = 0;
        if (res1.getInteger("retcode") == 0) {
            // step5:最后设置本地产品上线状态为0
            Map map1 = new HashMap();
            map1.put("rpId", rpId);
            map1.put("isOnline", 0);
            i = rpMapper.updateRpByMap(map1);
        }
        if (i > 0) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error();
        }
    }

    @Override
    public Map getRpPriceAndHotelObj(Map map) {
        String hotelId = map.get("hotelId").toString();
        String orderCode = map.get("orderCode").toString();
        String orderId = map.get("orderId").toString();
        // 订单信息
        Map orderInfo = orderMapper.getOrderByOrderId(orderId);
        // 订单采购价
        List<Map> rpPrice = orderMapper.getOrderPrice(orderId);
        // 订单对应酒店信息
        Map hotelObj = hotelMapper.getHotelObjByHotelId(hotelId);
        // 订单操作日期
        List<Map> orderLogList = logService.getOrderLogByOrderCode(orderCode);
        // 获取订单发单模板
        String hotelIssueConfig = hotelMapper.getHotelIssueConfig(hotelId);
        Map map1 = new HashMap();
        map1.put("orderInfo", orderInfo);
        map1.put("rpPrice", rpPrice);
        map1.put("hotelObj", hotelObj);
        map1.put("orderLogList", orderLogList);
        map1.put("hotelIssueConfig", hotelIssueConfig);
        return map1;
    }

    @Override
    public List<Map> getCgjByOrderId(Map map) {
        String orderId = map.get("orderId").toString();
        List<Map> rpPrice = orderMapper.getOrderPrice(orderId);
        return rpPrice;
    }

    @Override
    public int postYueYouEditCgj(String orderId,JSONArray jsonArray) {
        Map orderInfo = orderMapper.getOrderByOrderId(orderId);
        // 修改采购价
        int count = 0;
        BigDecimal cgjOriginal = new BigDecimal(0);
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject1 = jsonArray.getJSONObject(i);
            BigDecimal rpPrice = new BigDecimal(jsonObject1.get("rpPrice").toString());
            cgjOriginal = cgjOriginal.add(rpPrice);
            count += orderMapper.postUpdateOrderPrice(jsonObject1);
        }
        cgjOriginal = cgjOriginal.multiply(new BigDecimal(orderInfo.get("fjsNum").toString()));

        Map map1 = new HashMap();
        map1.put("orderId",orderId);
        map1.put("cgjOriginal",cgjOriginal);
        orderMapper.updateOrder(map1);
        return count;
    }
}